<template>
  <!-- http-request 覆盖默认的上传行为，可以自定义上传的实现 -->
  <!-- action 必选参数，上传的地址 -->
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <!-- 上传的+号  -->
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <!-- 进度条 -->
    <el-progress v-if="showProgress" class="progress" type="circle" :percentage="percent" />
  </el-upload>
</template>

<script>
// 下载引入cos(对象存储)
var COS = require('cos-js-sdk-v5')
// 实例化
const cos = new COS({
  SecretId: 'AKIDPbWBZfU2KL5YkeIekY5LJ1SbU6SXLs86',
  SecretKey: 'jBNIwIODl48sMaXDckaASTDgrlOjoc9P'
})

export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showProgress: false, // 进度条的展示
      percent: 100 // 进度条进度
    }
  },
  methods: {
    // 图片上传方法
    upload(files) {
    //   console.log(files)
      if (files.file) {
        this.showProgress = true
        //   将图片存储到腾讯云
        cos.putObject({
          Bucket: 'lqq-1308159134', /* 必须 存储桶名称 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须  文件名 */
          StorageClass: 'STANDARD', // 存储类型
          Body: files.file, // 上传文件对象
          onProgress: progressData => { // 上传进度
            // console.log(JSON.stringify(progressData))
            this.percent = progressData.percent * 100
          }
        }, (err, data) => { // 上传失败/成功的回调(这里需要使用箭头函数，改变this指向)
        //   console.log(err || data)
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https://${data.Location}`
            this.showProgress = false
          }
        })
      }
    },
    // 上传成功
    handleAvatarSuccess() {

    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style scoped>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
